package com.bear.atlassianmcp.oauth.controller;

import com.bear.atlassianmcp.oauth.model.OAuthToken;
import com.bear.atlassianmcp.oauth.service.OAuthService;
import com.bear.atlassianmcp.oauth.util.OAuthTokenParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * OAuth 回调控制器
 * 处理 Atlassian 服务器的 OAuth 授权回调
 */
@RestController
@RequestMapping("/oauth")
public class OAuthCallbackController {
    
    private static final Logger logger = LoggerFactory.getLogger(OAuthCallbackController.class);
    
    private final OAuthService oauthService;
    private final OAuthTokenParser tokenParser;

    @Autowired
    public OAuthCallbackController(OAuthService oauthService, OAuthTokenParser tokenParser) {
        this.oauthService = oauthService;
        this.tokenParser = tokenParser;
    }
    
    /**
     * 处理 Jira OAuth 授权回调
     */
    @GetMapping("/jira/callback")
    public ResponseEntity<String> handleJiraCallback(
            @RequestParam("oauth_token") String oauthToken,
            @RequestParam("oauth_verifier") String oauthVerifier) {
        
        logger.info("Received Jira OAuth callback - token: {}, verifier: {}", oauthToken, oauthVerifier);
        
        try {
            OAuthToken accessToken = oauthService.handleAuthorizationCallback(oauthToken, oauthVerifier);
            String tokenString = tokenParser.formatToAuthorizationHeader(accessToken);
            String successPage = buildSuccessPageWithToken("Jira", "您已成功授权 Jira 访问权限！", tokenString);
            return ResponseEntity.ok()
                    .header("Content-Type", "text/html; charset=UTF-8")
                    .body(successPage);

        } catch (Exception e) {
            logger.error("Failed to handle Jira OAuth callback: {}", e.getMessage(), e);
            String errorPage = buildErrorPage("Jira", "授权失败：" + e.getMessage());
            return ResponseEntity.badRequest()
                    .header("Content-Type", "text/html; charset=UTF-8")
                    .body(errorPage);
        }
    }
    
    /**
     * 处理 Confluence OAuth 授权回调
     */
    @GetMapping("/confluence/callback")
    public ResponseEntity<String> handleConfluenceCallback(
            @RequestParam("oauth_token") String oauthToken,
            @RequestParam("oauth_verifier") String oauthVerifier) {
        
        logger.info("Received Confluence OAuth callback - token: {}, verifier: {}", oauthToken, oauthVerifier);
        
        try {
            OAuthToken accessToken = oauthService.handleAuthorizationCallback(oauthToken, oauthVerifier);
            String tokenString = tokenParser.formatToAuthorizationHeader(accessToken);
            String successPage = buildSuccessPageWithToken("Confluence", "您已成功授权 Confluence 访问权限！", tokenString);
            return ResponseEntity.ok()
                    .header("Content-Type", "text/html; charset=UTF-8")
                    .body(successPage);

        } catch (Exception e) {
            logger.error("Failed to handle Confluence OAuth callback: {}", e.getMessage(), e);
            String errorPage = buildErrorPage("Confluence", "授权失败：" + e.getMessage());
            return ResponseEntity.badRequest()
                    .header("Content-Type", "text/html; charset=UTF-8")
                    .body(errorPage);
        }
    }
    
    /**
     * OAuth 状态检查端点
     */
    @GetMapping("/status")
    public ResponseEntity<String> getOAuthStatus() {
        try {
            boolean jiraEnabled = oauthService.hasValidToken(
                com.bear.atlassianmcp.oauth.model.OAuthToken.ServiceType.JIRA);
            boolean confluenceEnabled = oauthService.hasValidToken(
                com.bear.atlassianmcp.oauth.model.OAuthToken.ServiceType.CONFLUENCE);
            
            String status = "{\n" +
                    "  \"jira\": {\n" +
                    "    \"enabled\": " + jiraEnabled + ",\n" +
                    "    \"status\": \"" + (jiraEnabled ? "已授权" : "未授权") + "\"\n" +
                    "  },\n" +
                    "  \"confluence\": {\n" +
                    "    \"enabled\": " + confluenceEnabled + ",\n" +
                    "    \"status\": \"" + (confluenceEnabled ? "已授权" : "未授权") + "\"\n" +
                    "  }\n" +
                    "}";
            
            return ResponseEntity.ok()
                    .header("Content-Type", "application/json; charset=UTF-8")
                    .body(status);
            
        } catch (Exception e) {
            logger.error("Failed to get OAuth status: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }
    
    /**
     * 构建带有令牌的成功页面
     */
    private String buildSuccessPageWithToken(String serviceName, String message, String oauthToken) {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"zh-CN\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>" + serviceName + " OAuth 授权成功</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n" +
                "            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n" +
                "            margin: 0;\n" +
                "            padding: 0;\n" +
                "            display: flex;\n" +
                "            justify-content: center;\n" +
                "            align-items: center;\n" +
                "            min-height: 100vh;\n" +
                "        }\n" +
                "        .container {\n" +
                "            background: white;\n" +
                "            border-radius: 10px;\n" +
                "            padding: 40px;\n" +
                "            box-shadow: 0 10px 30px rgba(0,0,0,0.2);\n" +
                "            text-align: center;\n" +
                "            max-width: 600px;\n" +
                "            margin: 20px;\n" +
                "        }\n" +
                "        .success-icon {\n" +
                "            font-size: 64px;\n" +
                "            color: #4CAF50;\n" +
                "            margin-bottom: 20px;\n" +
                "        }\n" +
                "        h1 {\n" +
                "            color: #333;\n" +
                "            margin-bottom: 20px;\n" +
                "            font-size: 24px;\n" +
                "        }\n" +
                "        p {\n" +
                "            color: #666;\n" +
                "            font-size: 16px;\n" +
                "            line-height: 1.5;\n" +
                "            margin-bottom: 20px;\n" +
                "        }\n" +
                "        .token-container {\n" +
                "            background: #f5f5f5;\n" +
                "            border: 1px solid #ddd;\n" +
                "            border-radius: 5px;\n" +
                "            padding: 15px;\n" +
                "            margin: 20px 0;\n" +
                "            text-align: left;\n" +
                "        }\n" +
                "        .token-label {\n" +
                "            font-weight: bold;\n" +
                "            color: #333;\n" +
                "            margin-bottom: 10px;\n" +
                "        }\n" +
                "        .token-value {\n" +
                "            font-family: 'Courier New', monospace;\n" +
                "            font-size: 12px;\n" +
                "            word-break: break-all;\n" +
                "            background: white;\n" +
                "            padding: 10px;\n" +
                "            border: 1px solid #ccc;\n" +
                "            border-radius: 3px;\n" +
                "            color: #333;\n" +
                "        }\n" +
                "        .copy-btn {\n" +
                "            background: #4CAF50;\n" +
                "            color: white;\n" +
                "            border: none;\n" +
                "            padding: 12px 30px;\n" +
                "            border-radius: 5px;\n" +
                "            font-size: 16px;\n" +
                "            cursor: pointer;\n" +
                "            transition: background 0.3s;\n" +
                "            margin-right: 10px;\n" +
                "        }\n" +
                "        .copy-btn:hover {\n" +
                "            background: #45a049;\n" +
                "        }\n" +
                "        .close-btn {\n" +
                "            background: #666;\n" +
                "            color: white;\n" +
                "            border: none;\n" +
                "            padding: 12px 30px;\n" +
                "            border-radius: 5px;\n" +
                "            font-size: 16px;\n" +
                "            cursor: pointer;\n" +
                "            transition: background 0.3s;\n" +
                "        }\n" +
                "        .close-btn:hover {\n" +
                "            background: #555;\n" +
                "        }\n" +
                "        .instructions {\n" +
                "            background: #e3f2fd;\n" +
                "            border-left: 4px solid #2196F3;\n" +
                "            padding: 15px;\n" +
                "            margin: 20px 0;\n" +
                "            text-align: left;\n" +
                "        }\n" +
                "        .instructions h3 {\n" +
                "            margin-top: 0;\n" +
                "            color: #1976D2;\n" +
                "        }\n" +
                "        .instructions ol {\n" +
                "            margin: 10px 0;\n" +
                "            padding-left: 20px;\n" +
                "        }\n" +
                "        .instructions li {\n" +
                "            margin: 5px 0;\n" +
                "            color: #333;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"container\">\n" +
                "        <div class=\"success-icon\">✅</div>\n" +
                "        <h1>授权成功！</h1>\n" +
                "        <p>" + message + "</p>\n" +
                "        \n" +
                "        <div class=\"token-container\">\n" +
                "            <div class=\"token-label\">您的 OAuth 令牌：</div>\n" +
                "            <div class=\"token-value\" id=\"oauthToken\">" + (oauthToken != null ? oauthToken : "令牌生成失败") + "</div>\n" +
                "        </div>\n" +
                "        \n" +
                "        <div class=\"instructions\">\n" +
                "            <h3>📋 使用说明：</h3>\n" +
                "            <ol>\n" +
                "                <li>点击\"复制令牌\"按钮复制上面的 OAuth 令牌</li>\n" +
                "                <li>在您的 MCP 客户端中设置 Authorization 头</li>\n" +
                "                <li>参考格式：Authorization=OAuth 令牌</li>\n" +
                "                <li>现在您可以使用 OAuth 1.0a 认证访问 " + serviceName + " API</li>\n" +
                "            </ol>\n" +
                "        </div>\n" +
                "        \n" +
                "        <button class=\"copy-btn\" onclick=\"copyToken()\">📋 复制令牌</button>\n" +
                "    </div>\n" +
                "    \n" +
                "    <script>\n" +
                "        function copyToken() {\n" +
                "            const tokenElement = document.getElementById('oauthToken');\n" +
                "            const tokenText = tokenElement.textContent;\n" +
                "            \n" +
                "            if (navigator.clipboard) {\n" +
                "                navigator.clipboard.writeText(tokenText).then(function() {\n" +
                "                    alert('令牌已复制到剪贴板！');\n" +
                "                }).catch(function(err) {\n" +
                "                    fallbackCopyTextToClipboard(tokenText);\n" +
                "                });\n" +
                "            } else {\n" +
                "                fallbackCopyTextToClipboard(tokenText);\n" +
                "            }\n" +
                "        }\n" +
                "        \n" +
                "        function fallbackCopyTextToClipboard(text) {\n" +
                "            const textArea = document.createElement('textarea');\n" +
                "            textArea.value = text;\n" +
                "            document.body.appendChild(textArea);\n" +
                "            textArea.focus();\n" +
                "            textArea.select();\n" +
                "            \n" +
                "            try {\n" +
                "                const successful = document.execCommand('copy');\n" +
                "                if (successful) {\n" +
                "                    alert('令牌已复制到剪贴板！');\n" +
                "                } else {\n" +
                "                    alert('复制失败，请手动选择并复制令牌。');\n" +
                "                }\n" +
                "            } catch (err) {\n" +
                "                alert('复制失败，请手动选择并复制令牌。');\n" +
                "            }\n" +
                "            \n" +
                "            document.body.removeChild(textArea);\n" +
                "        }\n" +
                "        \n" +
                "        // 自动选择令牌文本以便手动复制\n" +
                "        document.getElementById('oauthToken').addEventListener('click', function() {\n" +
                "            const range = document.createRange();\n" +
                "            range.selectNodeContents(this);\n" +
                "            const selection = window.getSelection();\n" +
                "            selection.removeAllRanges();\n" +
                "            selection.addRange(range);\n" +
                "        });\n" +
                "    </script>\n" +
                "</body>\n" +
                "</html>";
    }
    
    /**
     * 构建错误页面
     */
    private String buildErrorPage(String serviceName, String errorMessage) {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"zh-CN\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>" + serviceName + " OAuth 授权失败</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n" +
                "            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);\n" +
                "            margin: 0;\n" +
                "            padding: 0;\n" +
                "            display: flex;\n" +
                "            justify-content: center;\n" +
                "            align-items: center;\n" +
                "            min-height: 100vh;\n" +
                "        }\n" +
                "        .container {\n" +
                "            background: white;\n" +
                "            border-radius: 10px;\n" +
                "            padding: 40px;\n" +
                "            box-shadow: 0 10px 30px rgba(0,0,0,0.2);\n" +
                "            text-align: center;\n" +
                "            max-width: 500px;\n" +
                "            margin: 20px;\n" +
                "        }\n" +
                "        .error-icon {\n" +
                "            font-size: 64px;\n" +
                "            color: #f44336;\n" +
                "            margin-bottom: 20px;\n" +
                "        }\n" +
                "        h1 {\n" +
                "            color: #333;\n" +
                "            margin-bottom: 20px;\n" +
                "            font-size: 24px;\n" +
                "        }\n" +
                "        p {\n" +
                "            color: #666;\n" +
                "            font-size: 16px;\n" +
                "            line-height: 1.5;\n" +
                "            margin-bottom: 20px;\n" +
                "        }\n" +
                "        .error-details {\n" +
                "            background: #f5f5f5;\n" +
                "            border-left: 4px solid #f44336;\n" +
                "            padding: 15px;\n" +
                "            margin: 20px 0;\n" +
                "            text-align: left;\n" +
                "            font-family: monospace;\n" +
                "            font-size: 14px;\n" +
                "            color: #333;\n" +
                "        }\n" +
                "        .retry-btn {\n" +
                "            background: #f44336;\n" +
                "            color: white;\n" +
                "            border: none;\n" +
                "            padding: 12px 30px;\n" +
                "            border-radius: 5px;\n" +
                "            font-size: 16px;\n" +
                "            cursor: pointer;\n" +
                "            transition: background 0.3s;\n" +
                "            margin-right: 10px;\n" +
                "        }\n" +
                "        .retry-btn:hover {\n" +
                "            background: #d32f2f;\n" +
                "        }\n" +
                "        .close-btn {\n" +
                "            background: #666;\n" +
                "            color: white;\n" +
                "            border: none;\n" +
                "            padding: 12px 30px;\n" +
                "            border-radius: 5px;\n" +
                "            font-size: 16px;\n" +
                "            cursor: pointer;\n" +
                "            transition: background 0.3s;\n" +
                "        }\n" +
                "        .close-btn:hover {\n" +
                "            background: #555;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"container\">\n" +
                "        <div class=\"error-icon\">❌</div>\n" +
                "        <h1>授权失败</h1>\n" +
                "        <p>很抱歉，" + serviceName + " OAuth 授权过程中出现了错误。</p>\n" +
                "        <div class=\"error-details\">" + errorMessage + "</div>\n" +
                "        <p>请检查配置并重试，或联系管理员获取帮助。</p>\n" +
                "        <button class=\"retry-btn\" onclick=\"history.back()\">重试</button>\n" +
                "        <button class=\"close-btn\" onclick=\"window.close()\">关闭页面</button>\n" +
                "    </div>\n" +
                "</body>\n" +
                "</html>";
    }
}
